package com.itjob.deep.servlet;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.itjob.deep.bean.UserBean;
import com.itjob.deep.util.CookieUtil;

public class InitServlet extends HttpServlet {

	private static final long serialVersionUID = -1763388443929755708L;

	@SuppressWarnings("unchecked")
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Cookie userCookie = CookieUtil.getCookie(request.getCookies(), "user");
		HttpSession session = request.getSession();
		ServletContext application = this.getServletContext();
		UserBean user = (UserBean)session.getAttribute("user");
		
		if (userCookie == null || userCookie.getValue() == null) {
			request.getRequestDispatcher("login.jsp").forward(request, response);
			return;
		} else if (user == null) {
			String username = URLDecoder.decode(userCookie.getValue(), "UTF-8");
			
			UserBean ub = new UserBean();
			ub.setUsername(username);
			ub.setGender("male");
			ub.setLoginTime(System.currentTimeMillis());
			
			session.setAttribute("user", ub);
			
			Map<String, UserBean> users = (Map<String, UserBean>) application.getAttribute("users");
			if (users == null) {
				users = new HashMap<String, UserBean>();
				application.setAttribute("users", users);
			}
			users.put(username, ub);
		}
		
		request.getRequestDispatcher("chat.jsp").forward(request, response);
	}
}
